// 接口域名
var apiHost='';        //正式环境
apiHost ='http://jdk.cn/';        //本地环境
// 统一请求方法
function request(option){     //url:接口地址,data:接口参数 ,msg:提示信息,fuc:执行函数,that:page的引用,用来更新视图

    var option = option ? option : {};    
    apiHost = option.apiHost ? option.apiHost : apiHost;    //api主网址,如果有该参数则用该参数的地址,没有则用默认设置地址
    var api = option.api ? option.api : '';   //api接口
    var data = option.data ? option.data : {};  //接口参数
    var loadingMsg = option.loadingMsg ? option.loadingMsg :false;  //加载信息
    var fn = option.fn ? option.fn : false; //成功回调函数
    var completeFn = option.completeFn ? option.completeFn : false; //完成调用回调函数
    var failFn = option.failFn ? option.failFn : false; //完成调用回调函数
    var successmsg = option.successmsg ? option.successmsg : false; //是否显示成功提示信息
    var failmsg = option.failmsg ? option.failmsg : false;    //是否显示失败提示信息
    var stopRefresh = option.stopRefresh ? option.stopRefresh : false;  //是否停止刷新
    var successCode = option.successCode ? option.successCode : 200;  //请求成功的code码,默认为200
    var method = option.method ? option.method : 'GET';  //请求成功的code码,默认为200
    var isGet=method=='GET';
    method=isGet?'GET':'POST';
    var header = isGet ? 
        { 'content-type': 'application/json' } : 
        { 'content-type': 'application/x-www-form-urlencoded' };
    if (loadingMsg){
        wx.showLoading({
          title: loadingMsg,
        })
      
    }
    wx.showNavigationBarLoading();    //导航栏显示加载动画
    wx.request({
        url: apiHost+api,
        data:data,
        method:method,
        header: header,
        success:function(res){
          
            var data=res.data;
            var code=res.data.code;
          
            if (code == successCode){
                if(successmsg){
                    toast(successmsg);
                }
                if(typeof(fn)=='function'){
                    fn(data.data);  //这是收到接口返回成功后的回调函数,参数是接口返回的数据
                }
            }else if(code==3){     //code=3是未登录
                app.toLogin();
            }else{
                if(failmsg){
                    toast(data.msg);
                }
                
            }
            
        },
        complete:function(){
            if(loadingMsg){
                setTimeout(()=>wx.hideLoading(),500);
            }
            wx.hideNavigationBarLoading();
            
            if (typeof (completeFn) == 'function') {
              completeFn();  //这是收到接口返回成功后的回调函数,参数是接口返回的数据
            }
        }
        
    })
}
// 获取用户ID
function getUserId(){
    
    var userId = wx.getStorageSync("userId");
    
    if (userId) {
        
        return userId;
    }
}

// 显示提示信息
function toast(msg){
    setTimeout(() => {
        wx.showToast({
            title: msg,
            icon: 'none'
        })
    }, 600)
}
// 检测是否登录,如果没登录则跳转至登录页面
function checkLogin(func){
    var userId=wx.getStorageSync("userId");
    if(!userId){
       
        return false;
        //login(func);
    }else{
        return true;
    }
}

//字符串去掉空格
function trim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}
//登录方法
function login(func){
    var api='login/weixin';
    wx.login({
        success:function(res){
            if(res.code){                            
                request(api,{code:res.code},'',function(content){
                    wx.setStorageSync('userId', content.userId);
                    wx.setStorageSync('is_full', content.is_full);
                    func();
                    
                });
            }else{
                toast('登录失败');
            }
        }
    })
}
//页面返回并返新
function back_refresh(){  
  var pages = getCurrentPages();
  pages[pages.length - 2].onLoad();   //回退并刷新
  wx.navigateBack({})
}
function navToJd(spreadUrl) {

  var two2oneurl = "/pages/jingfen_twotoone/item?spreadUrl="+spreadUrl;
  //var buyurl = options.buyurl;
  //重新组织目标页完整路径，加上已编码的联盟推广链接
  //path = two2oneurl.replace("spreadUrl=", "spreadUrl=" + buyurl);
  wx.navigateToMiniProgram({
    appId: 'wx13e41a437b8a1d2e',
    path: two2oneurl,
    success: function (res) {
      console.log(res);
    },
    fail: function (res) {
      console.log(res);
    }
  })
  return;
}
//urlencode编码
function URLEncode (clearString) {
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9-_.]*)/;
    while (x < clearString.length) {
      var match = regex.exec(clearString.substr(x));
      if (match != null && match.length > 1 && match[1] != '') {
          output += match[1];
       x += match[1].length;
     } else {
       if (clearString.substr(x, 1) == ' ') {
         //原文在此用 clearString[x] == ' ' 做判断, 但ie不支持把字符串当作数来访问, 
         //修改后两种浏览器都可兼容 
         output += '+';
       }
       else {
         var charCode = clearString.charCodeAt(x);
         var hexVal = charCode.toString(16);
         output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
     }
   }
   return output;
 }
//去掉数组中不存在某参数的数据
function trim_array(array){
    var nanNum=0;   //无优惠券的商品数量
    
    for (var i in array){
        var j=i-nanNum;
        var value=array[j];
        //console.log(i);
        //debugger;
        if (!value.couponList ||value.couponList.length<=0){
            console.log(i+'无优惠券');
            console.log(typeof (value.couponList) == 'undefined');
            array.splice(j,1);
            nanNum++;
        }
    }
    return array;
}
module.exports = {
    login:login,
    request:request,
    trim_array: trim_array,
    toast:toast,
  URLEncode: URLEncode,
    trim:trim,
    navToJd: navToJd,
    back_refresh: back_refresh,
}